export const initChatRobot = (livechatId: string | null)=>{
    // livechatId = '14128425'
    function parseLink() {
        let obj = Object.create(null);
        let _url = window.location.search;
        let _search = _url.substring(_url.indexOf("?") + 1);
        let _reg = /([^?&=]+)=([^?&=]*)/g;
        _search.replace(_reg, (rs, $1, $2) => {
          let _name = decodeURIComponent($1);
          let _val = decodeURIComponent($2);
          obj[_name] = _val;
          return rs;
        });
        return obj;
    }
    (function (d, s, id) {
      let js:any, fjs:any = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s); js.id = id;
      js.src = 'https://connect.facebook.net/zh_CN/sdk.js#xfbml=1&version=v2.12&appId=1136339393550769&autoLogAppEvents=1';
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
    function initChat(a?:any) {
      (window as any).__lc = (window as any).__lc || {};
      (window as any).__lc.license = livechatId;

      if (livechatId && livechatId.toString().length <= 10) {
        ;
        (function (n, t, c) {
          function i(n:any) {
            return e._h ? (e._h as any).apply(null, n) :
              (e._q as any).push(n)
          }
          var e = {
            _q: [],
            _h: null,
            _v: "2.0",
            on: function () {
              i(["on", c.call(arguments)])
            },
            once: function () {
              i(["once", c.call(arguments)])
            },
            off: function () {
              i(["off", c.call(arguments)])
            },
            get: function () {
              if (!e._h) throw new Error("[LiveChatWidget] You can't use getters before load.");
              return i(["get", c.call(arguments)])
            },
            call: function () {
              i(["call", c.call(arguments)])
            },
            init: function () {
              let n:any = t.createElement("script");
              n.async = !0, n.type = "text/javascript",
              n.src = "https://cdn.livechatinc.com/tracking.js", t.head.appendChild(n)
            }
          };
          !(n as any).__lc.asyncInit && e.init(),
            (n as any).LiveChatWidget = (n as any).LiveChatWidget || e
        }(window, document, [].slice));
        ;(window as any).LiveChatWidget = LiveChatWidget;
        LiveChatWidget.on('ready', () => {
          // console.log("mini mize")
          let isH5 = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
          // if (isH5) {
          //   LiveChatWidget.call('hide')
          // }
        })
        LiveChatWidget.on('visibility_changed', () => {
          // if (data.visibility === "minimized") {
          // LiveChatWidget.call('hide')
          // }
        })
      } else if (livechatId !== null){
        // console.log(window.zESettings);
        var url = "https://static.zdassets.com/ekr/snippet.js?key=" + livechatId
        // console.log(url);
        // localStorage.setItem("licenseId" ,url)
        // LiveChatWidget.on('ready', () => {
        //   var script = document.createElement('script');
        //   script.type = 'text/javascript';
        //   script.id = 'ze-snippet';
        //   script.async = true;
        //   script.src = url;
        //   document.getElementsByTagName('head')[0].appendChild(script)
        // })
        // LiveChatWidget.on('visibility_changed', (data) => {
        //   document.getElementsByTagName('head')[0].removeChild(document.getElementById('ze-snippet'))
        //   // if (data.visibility === "minimized") {
        //     // LiveChatWidget.call('hide')
        //   // }
        // })
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.id = 'ze-snippet';
        script.async = true;
        script.src = url;
        document.getElementsByTagName('head')[0].appendChild(script)
        // console.log(document.getElementById('ze-snippet'));
        // console.log(document.getElementsByTagName('head')[0]);
        // document.getElementsByTagName('head')[0].removeChild(document.getElementById('ze-snippet'))
        // if(localStorage.getItem("kefu") != false){
        // }else{
        //   document.getElementById('ze-snippet').remove()
        // }
      }
    }
    let data:any = parseLink();
    // console.log('parseLink >>>>>>>>>', data);
    if (data.channel) {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
          var res = JSON.parse(this.responseText);
          var data:any = res.data;
          localStorage.setItem('channel_info', JSON.stringify(data));
          initChat(data.livechatId);
        }
      }
      xhttp.open('GET', import.meta.env.VITE_API_BASEURL + '/hall/playChannel/getChannelInfo?channel=' + data.channel, true);
      // xhttp.open('GET', 'https://pre-api.realone.io/hall/playChannel/getChannelInfo?channel=' + data.channel, true);
      xhttp.send();
    } else {
      initChat(livechatId);
    }
}

export default initChatRobot;
